import os
from datetime import datetime, timedelta
from config import get_config
from pathlib import Path

def get_log_files():
    conf_data = get_config()
    config = dict(conf_data)
    suffix = config.get("suffix", ".gz")
    level = config.get("level", "debug")
    time_scope = config.get("time_scope", 1)
    time_format = config.get("time_format", '%Y-%m-%d ')
    log_dir = config.get("logdir", os.getcwd())

    # print(time_scope, type(time_scope))

    target_file = []

    for root, dirs, files in os.walk(log_dir):
        # print(files)
        for file in files:
           if filename_check_all(filename=file,suffix=suffix,level=level,time_scope=time_scope,
                                 time_format=time_format,log_dir=log_dir):
               target_file.append(os.path.join(log_dir, file))

    return target_file


def filename_check_all(filename: str, suffix, level, time_scope,time_format,log_dir):
    file_path = Path(os.path.join(log_dir, filename))
    if file_path.is_dir():
        return False

    filename = filename.lower()
    return suffix_check(filename, suffix) and level_check(filename, level) and time_scope_check(filename, time_scope,time_format)


def suffix_check(filename, suffix) -> bool:
    return filename.endswith(suffix)


def level_check(filename: str, level: str) -> bool:
    if level == 'all':
        return True
    return level.lower() in filename


def time_scope_check(filename: str, time_scope: int,time_format:str) -> bool:
    if time_scope >0:
        return True
    now = datetime.now()
    sub = timedelta(days=abs(time_scope))
    target_time = now - sub
    target_time_str = target_time.strftime(time_format)
    return target_time_str in filename


